//
//  NewsDetailTableViewController.m
//  LWB_Project
//
//  Created by 王剑亮 on 15/11/13.
//  Copyright © 2015年 wangjianliang. All rights reserved.
//

#import "NewsDetailTableViewController.h"
#import "JSONAnalysis.h"
#import "NewsDetailModel.h"
#import "NewsDetailImgModel.h"
#import "WNetDealTools.h"
#import "UIImageView+WebCache.h"
#import "NewsPicture.h"
#import "MBProgressHUD.h"

@interface NewsDetailTableViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) NewsDetailModel *detailModel;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) NSString *wordSize;

@property (nonatomic, strong) UIScrollView *myscrollView;

@property (nonatomic,retain) MBProgressHUD * hud;//菊花图标

@end

@implementation NewsDetailTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    
    if (_model.photosetID!=nil)
    {
        [self loadScrollView];
    }else
    {
        #pragma mark--- 如果是第一种类型的界面 那么将进行webView显示Html的数据
        [self loadWebView];
    }
    
    //加载图标
    [self p_setupProgressHud];
}
#pragma mark--- 初始化菊花图标
-(void)p_setupProgressHud{
    
    self.hud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width , self.view.frame.size.height)];
    self.hud.frame = self.view.bounds;
    self.hud.minSize = CGSizeMake(100, 100);
    self.hud.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:self.hud];
    self.hud.dimBackground = YES;
    self.hud.labelText = @"loading";
    self.hud.backgroundColor = [UIColor clearColor];
    [self.hud show:YES];
    
}

#pragma mark--- 第一个界面的加载资源

-(void)loadWebView
{
    #pragma mark--- 添加上webView
    self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    self.webView.delegate = self;
    self.webView.scalesPageToFit = NO;
    //    self.webView.scrollView.bounces = NO;
    [self.view addSubview:self.webView];
    
    //处理数据源并且处理好显示在WebView上
    [self dealWebViewdatasource];
    
}

-(void)dealWebViewdatasource
{
#pragma mark--- 获取网络资源
    NSString *urlStr = nil;
    
    if (_model.docid == nil)
    {
        urlStr = _model.url_3w;
        
    } else
    {
        urlStr = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", _model.docid];
    }
    
    //第三方的数据下载 这是移植的能用就好！
    JSONAnalysis *json = [[JSONAnalysis alloc] initWithGETRequest:urlStr];
    
    [json didFinishUsingBlock:^(id jsonObject)
     {
         //数据解析
         NSDictionary *dict = jsonObject[_model.docid];
         NewsDetailModel *detail = [[NewsDetailModel alloc] init];
         detail.title = dict[@"title"];
         detail.ptime = dict[@"ptime"];
         detail.body = dict[@"body"];
         
         NSArray *imgArray = dict[@"img"];
         NSMutableArray *temArray = [NSMutableArray arrayWithCapacity:imgArray.count];
         
         for (NSDictionary *dict in imgArray) {
             NewsDetailImgModel *imgModel = [NewsDetailImgModel detailImgWithDict:dict];
             [temArray addObject:imgModel];
         }
         detail.img = temArray;
         self.detailModel = detail;
         //解析数据完事
         
         //开始显示webview
         [self showInWebView];
         
     }];


}

#pragma mark - ******************** 拼接html语言
- (void)showInWebView
{
    NSMutableString *html = [NSMutableString string];
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendFormat:@"<link rel=\"stylesheet\" href=\"%@\">",[[NSBundle mainBundle] URLForResource:@"SXDetails.css" withExtension:nil]];
    [html appendString:@"</head>"];
    
    [html appendString:@"<body>"];
    [html appendString:[self touchBody]];
    [html appendString:@"</body>"];
    [html appendString:@"</html>"];
    
    //显示处理之后的html 语言的文字
    [self.webView loadHTMLString:html baseURL:nil];
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //隐藏菊花
        [self.hud hide:YES];
    });

}

#pragma mark--- 获取里边的信息
- (NSString *)touchBody
{
    NSMutableString *body = [NSMutableString string];
    [body appendFormat:@"<div class=\"title\">%@</div>",self.detailModel.title];
    [body appendFormat:@"<div class=\"time\">%@</div>",self.detailModel.ptime];
    if (self.detailModel.body != nil) {
        [body appendString:self.detailModel.body];
    }
    // 遍历img
    for (NewsDetailImgModel *detailImgModel in self.detailModel.img) {
        NSMutableString *imgHtml = [NSMutableString string];

        // 设置img的div
        [imgHtml appendString:@"<div class=\"img-parent\">"];
        
        // 数组存放被切割的像素
        NSArray *pixel = [detailImgModel.pixel componentsSeparatedByString:@"*"];
        CGFloat width = [[pixel firstObject]floatValue];
        CGFloat height = [[pixel lastObject]floatValue];
        // 判断是否超过最大宽度
        CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width * 0.96;
        if (width > maxWidth) {
            height = maxWidth / width * height;
            width = maxWidth;
        }
        
        NSString *onload = @"this.onclick = function() {"
        "  window.location.href = 'sx:src=' +this.src;"
        "};";
        [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%f\" height=\"%f\" src=\"%@\">",onload,width,height,detailImgModel.src];
        // 结束标记
        [imgHtml appendString:@"</div>"];
        // 替换标记
        [body replaceOccurrencesOfString:detailImgModel.ref withString:imgHtml options:NSCaseInsensitiveSearch range:NSMakeRange(0, body.length)];
    }
    return body;
}

#pragma mark - UIWebViewDelegate
// 取消当前页面所有点击事件
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //判断是否是单击
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        //NSLog(@"截获单击事件");
        return NO;
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *number = nil;
    
    if ([self.wordSize isEqualToString:@"0"]) {
        number = @"80%";
    } else if ([self.wordSize isEqualToString:@"1"]) {
        number = @"100%";
    } else {
        number = @"120%";
    }
    
    // 调整字体大小   body  '100%'  可做更改
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@'", number]];
}

#pragma mark--- 第一个界面的加载资源完毕！


#pragma mark--- 创建第二个界面scrollView
-(void)loadScrollView
{

     #pragma mark--- 创建一个ScrollView
    UIScrollView *_scrollview;
    _scrollview = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _scrollview.backgroundColor = [UIColor whiteColor];
    _scrollview.showsHorizontalScrollIndicator = NO;
    _scrollview.showsVerticalScrollIndicator = YES;
    _scrollview.pagingEnabled = YES;
    self.myscrollView = _scrollview;
    [self.view addSubview:self.myscrollView];

    #pragma mark--- 下载数据 
    [WNetDealTools dealCellModelPhotosetID:_model.photosetID block:^(NSArray *ModelArray) {

       //拿到model数组 进行放到ScrollView上imageView
       self.myscrollView.contentSize = CGSizeMake(self.view.frame.size.width*ModelArray.count, self.view.frame.size.height);

        #pragma mark--- imageView添加到ScrollView上 
        NSInteger i = 0;
        for (NewsPicture *model in ModelArray) {

            
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.frame =  CGRectMake((i++)* self.view.frame.size.width, self.view.frame.size.height/4, self.view.frame.size.width, self.view.frame.size.height/2);
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.imageUrl]];
            [self.myscrollView addSubview:imageView];
            
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //隐藏菊花
            [self.hud hide:YES];
        });

    }];
    
    

    

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
